package com.ym.medical.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.yunxin.YunXinApiUtil;
import com.ym.medical.dao.YunxinUserDao;
import com.ym.medical.domain.bo.YunxinSyncDataVo;
import com.ym.medical.domain.entity.UserEntity;
import com.ym.medical.domain.entity.YunxinUserEntity;
import com.ym.medical.domain.param.YunxinUserParam;
import com.ym.medical.service.IUserSV;
import com.ym.medical.service.IYunxinUserSV;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;

/**
 * 云信Service业务层处理
 *
 * @author ym
 * @date 2020-08-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class YunxinUserSVImpl extends BaseSVImpl<YunxinUserEntity, YunxinUserDao> implements IYunxinUserSV {

	private static final Logger LOGGER = LoggerFactory.getLogger(YunxinUserSVImpl.class);

	@Autowired
	private IUserSV userSV;


	@Override
	public long save(YunxinUserEntity yunxinYunxinUser) {
		return insert(yunxinYunxinUser);
	}

	@Override
	public YunxinUserEntity findById(long yunxinYunxinUserId) {
		return this.selectById(yunxinYunxinUserId);
	}

	@Override
	public YunxinUserEntity findByModel(YunxinUserParam yunxinUserParam) {
		List<YunxinUserEntity> yunxinYunxinUsers = list(yunxinUserParam);
		return yunxinYunxinUsers.isEmpty() ? null : yunxinYunxinUsers.get(0);
	}

	@Override
	public List<YunxinUserEntity> list(YunxinUserParam yunxinYunxinUserModel) {
		return this.selectList(yunxinYunxinUserModel.covert());
	}

	@Override
	public void updateYunxinAcc(Long userId) {
		List<YunxinUserEntity> userList = this.selectList(YunxinUserEntity.builder().userId(userId).build());
		if (!userList.isEmpty()) {
			String accid = userList.get(0).getAccid();
			UserEntity userModel = userSV.findById(userId);
			YunXinApiUtil.updateInfo(
					accid
					, userModel.getRealName()
					, userModel.getHeadUrl()
					, String.valueOf(userModel.getSignId())
					, userModel.getPhoneNo()
					, userModel.getSex()
					, userModel.getUserType()
			);
		}

	}


	@Override
	public void syncMessages(String body) {
		YunxinSyncDataVo yunxinSyncDataVo = JSONObject.parseObject(body, YunxinSyncDataVo.class);
		LOGGER.info("处理消息开始:" + System.currentTimeMillis());
		LOGGER.info("内容:" + body);
		String eventType = yunxinSyncDataVo.getEventType();
		switch (eventType) {
			// 表示CONVERSATION消息，即会话类型的消息（目前包括P2P聊天消息，群组聊天消息，群组操作，好友操作）
			case "1":
				handlingTwoPersonSessionData(yunxinSyncDataVo);
				break;
			default:
				LOGGER.error("异常消息!");
		}
		LOGGER.info("处理消息结束:" + System.currentTimeMillis());
	}

	/**
	 * 处理二人会话聊天数据
	 *
	 * @param yunxinSyncDataVo
	 */
	public void handlingTwoPersonSessionData(YunxinSyncDataVo yunxinSyncDataVo) {
		String convType = yunxinSyncDataVo.getConvType();
		if ("PERSON".equals(convType)) {// 标识二人会话数据
			// todo
		}
	}

	/**
	 * 医生当前患者云信id
	 *
	 * @param doctId
	 * @param userId
	 * @return
	 */
	@Override
	public List<YunxinUserEntity> selectYunXinId(Long doctId, Long userId) {
		return mapper.selectYunXinId(doctId, userId);
	}

	@Override
	public YunxinUserEntity createYxUserAccount(UserEntity userEntity) {
		YunxinUserEntity yunxin = this.selectOne(SelectWhere().andEqualTo(YunxinUserEntity::getUserId, userEntity.getId()).end());
		if (yunxin == null) {
			yunxin = new YunxinUserEntity();
			String accId = IdUtil.fastSimpleUUID();
			String yxPwd = YunXinApiUtil.registerAcc(
					accId
					, userEntity.getRealName()
					, userEntity.getHeadUrl()
					, String.valueOf(userEntity.getSignId())
					, userEntity.getPhoneNo()
					, userEntity.getSex()
					, userEntity.getUserType()
			);
			if (yxPwd != null) {
				yunxin.setUserId(userEntity.getId());
				yunxin.setAccid(accId);
				yunxin.setToken(yxPwd);
				this.insert(yunxin);
				log.info("云信账户创建成功!");
			}
		}
		return yunxin;
	}
	@Override
	public YunxinUserEntity createYunxinAcc(Long userId) {
		YunxinUserEntity yunxin = new YunxinUserEntity();
		YunxinUserParam yunxinUserModel = new YunxinUserParam();
		yunxinUserModel.setUserId(userId);
		if (this.findByModel(yunxinUserModel) == null) {
			UserEntity user = SpringUtil.getBean(IUserSV.class).findById(userId);
			String accId = UUID.randomUUID().toString().replace("_","");
			String yxPwd = YunXinApiUtil.registerAcc(
					accId,
					user.getRealName(),
					user.getHeadUrl(),
					String.valueOf(user.getSignId()),
					user.getPhoneNo(),
					user.getSex(),
					user.getUserType()
			);
			if (yxPwd != null) {
				yunxin.setName(user.getRealName());
				yunxin.setIcon(user.getHeadUrl());
				yunxin.setUserId(userId);
				yunxin.setAccid(accId);
				yunxin.setToken(yxPwd);
				this.save(yunxin);
				LOGGER.info("云信账户创建成功!");
			}
		}
		return yunxin;
	}
}
